﻿using System.Net.Http.Headers;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using ConsoleApp.DispatchTask;
using ConsoleApp.Middleware;
using ConsoleApp.Model.Entity;
using ConsoleApp.Service;
using Microsoft.EntityFrameworkCore;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;


try
{
    Serve.Run(RunOptions.Default
        .ConfigureBuilder(builder =>
        {
            builder.Services.AddDbContext<AutoDingContext>(opt =>
            {
                string connectionString = builder.Configuration.GetConnectionString("MySQLConnection");
                var serverVersion = ServerVersion.AutoDetect(connectionString);
                opt.UseMySql(connectionString, serverVersion);
            });
            builder.Services.AddScoped<IHttpService, HttpService>();
            builder.Services.AddScoped<IDbService, DbService>();


            #region 注入 Quartz调度类

            builder.Services.AddSingleton<Dispatch>();
            builder.Services.AddTransient<SendMessageJob>(); // 这里使用瞬时依赖注入
            builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>(); //注册ISchedulerFactory的实例。
            builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();

            #endregion

            builder.Services.AddControllers()
                .AddInject().AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                }).AddMvcOptions((opt) => { opt.Filters.Add<ApiAuthorizeAttribute>(); });
        })
        .Configure(app =>
        {
            //获取前面注入的Quartz调度类
            var quartz = app.Services.GetRequiredService<Dispatch>();
            app.Lifetime.ApplicationStarted.Register(() => { quartz.Init().GetAwaiter().GetResult(); });
            app.Lifetime.ApplicationStopped.Register(() => { quartz.Stop(); });

            app.UseMiddleware<JwtMiddleware>();
            app.UseMiddleware<RealIpMiddleware>();
            app.UseRouting();
            app.UseCorsAccessor();
            app.UseAuthorization();
            app.UseInject(string.Empty);
            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }));
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}